package com.albert.activitystreamdemo.controller;

import com.albert.activitystreamdemo.entity.ActivityParam;
import com.albert.activitystreamdemo.entity.Leave;
import com.albert.activitystreamdemo.entity.StaticParam;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @auther cyq
 * @create 17:48 2021/3/2
 */
@RestController
@ResponseBody
@RequestMapping("/leave")
public class LeaveController {
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;

    /**
     * @description: 执行流程
     * @auther: cyq
     * @create: 9:56 2021/3/5
     */
    @RequestMapping("/eccute")
    public String activityExcute(@RequestBody ActivityParam activityParam) {
        String operationType = activityParam.getOperationType();
        if (operationType.isEmpty()) {
            return "操作类行为必须apply、approve、reapply";
        } else if (StaticParam.ACTIVITY_OPERATE_TYPE_APPLY.equals(operationType)) {
            // 调用发起申请方法
            return applyProcess(activityParam);
        } else if (StaticParam.ACTIVITY_OPERATE_TYPE_APPROVE.equals(operationType)) {
            // 调用审批方法
            return approveProcess(activityParam);
        } else if (StaticParam.ACTIVITY_OPERATE_TYPE_REAPPLY.equals(operationType)) {
            // 调用申请者再申请方法
            return reApplyProcess(activityParam);
        } else {
            return "请求操作类型不存在";
        }
    }
    /**
     * @description: 被驳回申请重新提交
     *
     * @auther: cyq
     * @create: 15:49 2021/3/5
     */
    private String reApplyProcess(ActivityParam activityParam) {
        String name = activityParam.getName();
        String nextApprove = activityParam.getNextApprove();
        if (name.isEmpty()) {
            return "当前审批处理人不能为空";
        } else if (nextApprove.isEmpty()) {
            return "流程下级审批人不能为空";
        }
        List<Task> T = taskService.createTaskQuery().taskAssignee(name).list();
        if (!ObjectUtils.isEmpty(T)) {
            System.out.println(name + "名下待重新发起事项数量：" + T.size());
            Task item = T.get(0);
            Map<String, Object> variables = new HashMap<>();
            variables.put("rejl", nextApprove);
            variables.put("inputUser", name);
            item.setAssignee("name");
            //完成此次审批。由下节点审批
            taskService.complete(item.getId(), variables);
            return name+"重新发起申请成功，下级审批人"+nextApprove;
        } else {
            return  name + "没有待重新发起申请";
        }

    }


    /**
     * @description: 流程审批操作
     *
     * @auther: cyq
     * @create: 10:14 2021/3/5
     */
    private String approveProcess(ActivityParam activityParam) {
        String name = activityParam.getName();
        String nextApprove = activityParam.getNextApprove();
        String isSuccess = activityParam.getIsSuccess();
        if (name.isEmpty()) {
            return "当前审批处理人不能为空";
        } else if (nextApprove.isEmpty()) {
            return "流程下级审批人不能为空";
        }else if (isSuccess.isEmpty()){
            return "当前操作审批决定为空";
        }
        List<Task> T = taskService.createTaskQuery().taskAssignee(name).list();
        if (!ObjectUtils.isEmpty(T)) {
            System.out.println(name + "名下代办事项数量：" + T.size());
            Task item = T.get(0);
            Map<String, Object> variables = new HashMap<>();
            variables.put("zjl", nextApprove);
            variables.put("isSuccess", isSuccess);
            item.setAssignee(name);
            //设置本地参数。在myListener1监听中获取。防止审核通过进行驳回
            taskService.setVariableLocal(item.getId(), "isSuccess", isSuccess);
            if ("true".equals(isSuccess)){
                //增加审批备注
                taskService.addComment(item.getId(), item.getProcessInstanceId(), "人事经理" + name + "同意");
            }
            //完成此次审批。由下节点审批
            taskService.complete(item.getId(), variables);
            if ("true".equals(isSuccess)){
                return "人事经理审批" + name + "通过";
            }else {
                return "人事经理审批" + name + "驳回申请";
            }
        } else {
            return "人事经理审批" + name + "没有代办任务";
        }

    }
    /**
     * @description: 申请流程
     *
     * @auther: cyq
     * @create: 10:37 2021/3/5
     */
    private String applyProcess(ActivityParam activityParam) {
        String name = activityParam.getName();
        String nextApprove = activityParam.getNextApprove();
        String processKey = activityParam.getProcessDefindKey();
        if (name.isEmpty()) {
            return "流程申请人不能为空";
        } else if (nextApprove.isEmpty()) {
            return "流程下级审批人不能为空";
        } else if (processKey.isEmpty()) {
            return "流程定义不能为空";
        }
        Map<String, Object> variables = new HashMap<>();
        //inputUser就是在bpmn中Assignee配置的参数
        variables.put("inputUser", name);
        variables.put("rsjl", nextApprove);
        //variables.put("zjl", "总经理");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey, variables);
        Task tmp = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId())
                .singleResult();
        tmp.setAssignee(name);
        //完成此节点。由下一节点审批。完成后act_ru_task会创建一条由下节点审批的数据
        taskService.complete(tmp.getId(), variables);
        return "申请者" + name + "成功发起请假申请下级审批人" + nextApprove;
    }


    @RequestMapping("/approve/{approve1Name}/{approve2Name}")
    public String approve(@PathVariable("approve1Name") String approve1Name, @PathVariable("approve2Name") String approve2Name) {
        List<Task> T = taskService.createTaskQuery().taskAssignee(approve1Name).list();
        if (!ObjectUtils.isEmpty(T)) {
            System.out.println(approve1Name + "名下代办事项数量：" + T.size());
            Task item = T.get(0);
            Map<String, Object> variables = new HashMap<>();
            variables.put("zjl", approve2Name);
            variables.put("isSuccess", true);
            item.setAssignee("人事经理");
            //设置本地参数。在myListener1监听中获取。防止审核通过进行驳回
            taskService.setVariableLocal(item.getId(), "isSuccess", true);
            //增加审批备注
            taskService.addComment(item.getId(), item.getProcessInstanceId(), "人事经理" + approve1Name + "同意");
            //完成此次审批。由下节点审批
            taskService.complete(item.getId(), variables);
            return "人事经理审批" + approve1Name + "通过";
        } else {
            return "人事经理审批" + approve1Name + "没有代办任务";
        }

    }

}
